package sp.service.impl;

import java.util.Set;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sp.dao.user.UserDao;
import sp.pojo.User;
import sp.service.UserService;
import sp.util.constant.SysConstant;

@Service("userService")
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserDao userDao;
	
/*	@Autowired
	private MailService mailService;
	
	@Autowired
	private RedisAPI redisApi;*/
	
	/**
	 * 新增用户
	 * 持久化前需要将密码散列并加上随机盐
	 * 新盐: 用户名+随机盐
	 */
	@Override
	public boolean txsaveUser(User user) throws Exception {
		if (null != user) {
			encrypPassWord(user);
			/*//首先验证用户是否邮箱登录
			if (user.getTypeCode().matches(SysConstant.EMIAL_RESP)){
				//发送激活码
				String activeCode = GenerateCodeUtil.getActiveCode();
				//mailService.sendActivateCode(user.getTypeCode(), activeCode);
				//30分钟有效期
				redisApi.set("activeCode:"+user.getTypeCode(), activeCode, 30*60);
				
				//封装持久化对象
				user.setIsStart(0);
				user.setEmail(user.getTypeCode());
				user.setCreateDate(new Date(System.currentTimeMillis()));
				user.setRoleId(2);
			}*/
			//保存
			return userDao.saveUser(user);
		}
		return false;
	}
	
	@Override
	public boolean txactiveEmail(String email) throws Exception {
		User user= userDao.findUserByUserName(email);
		if (user != null) {
			user.setIsStart(1);
			return userDao.modifyUser(user);
		}
		return false;
	}


	@Override
	public User findUserByName(String username){
		//具体密码匹配交给shiro处理
		return userDao.findUserByUserName(username);
	}

	
	
	@Override
	public boolean deleteUser(Integer uid) throws Exception {
		return userDao.deleteUser(uid);
	}

	@Override
	public boolean modifyUser(User user) throws Exception {
		User oldUser = userDao.findUserByUserName(user.getTypeCode()); 
		if (null != oldUser && !oldUser.getPassword().equals(user.getPassword())) {
			encrypPassWord(user);
		}
		return userDao.modifyUser(user);
	}

	
	/**
	 * 新增和修改用户密码时需要加密
	 * @param user
	 */
	private void encrypPassWord(User user) {
		String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
		SimpleHash hash = new SimpleHash(SysConstant.ALGORITHM, user.getPassword(), 
								user.getTypeCode() + salt, SysConstant.HASH_ITERATIONS); 
		user.setPassword(hash.toHex());
		user.setSalt(salt);
		
	}

	@Override
	public Set<String> findRoles(String typeCode) throws Exception {
		return userDao.findRoles(typeCode);
	}

	@Override
	public Set<String> findPermissions(String typeCode) throws Exception {
		return userDao.findPermissions(typeCode);
	}
	
}
